package com.gzy.rpsm_property.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gzy.rpsm_property.mapper.UserMapper;
import com.gzy.rpsm_property.pojo.*;
import com.gzy.rpsm_property.service.UserService;
import com.gzy.rpsm_property.utils.EncryptionUtil;
import com.gzy.rpsm_property.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public int insertUser(User user) throws DuplicateKeyException, Exception {
        int result = -1;
        result = userMapper.insertUser(user);
        return result;
    }

    @Override
    public int changeUser(User user) {
        return userMapper.changeUser(user);
    }

    @Override
    public User queryById(int id) {
        return userMapper.queryById(id);
    }

    @Override
    public PageResult<User> pageOfOwner(int current, int size) {
        PageHelper.startPage(current, size);
        Page<User> page = userMapper.owners();
        return PageResult.restPage(page);
    }

    @Override
    public List<Amount> getUnpaidAmountsByRoomId(Integer roomId) {
        return userMapper.getUnpaidAmountsByRoomId(roomId);
    }

    @Override
    public User login(String account, String password) {
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        User user = userMapper.queryByAccountAndPassword(account, password);
        if (user == null) {
            return null;
        }
        // 直接使用 Integer 类型的 user.getUserid()
        Integer userId = user.getUserid();
        String token = TokenUtil.generateToken(userId); // 登录成功，生成token
        user.setToken(token); // 将设置到user的token字段中
        return user;
    }



    @Override
    public Page<Amount> getUnpaidAmountsByRoomId(Integer roomId, int page, int size) {
        PageHelper.startPage(page, size);
        return (Page<Amount>) userMapper.getUnpaidAmountsByRoomId(roomId);
    }
    @Override
    public int payAmount(int amountId) {
        return userMapper.payAmount(amountId);
    }

    @Override
    public List<Ms> getAllMessagesWithUserDetails() {
        return userMapper.getAllMessagesWithUserDetails();
    }

    @Override
    public Optional<User> getUserByUsername(String username) {
        User user = userMapper.getUserByUsername(username);
        return Optional.ofNullable(user);
    }
@Override
    public int activateUser(int userid) {
        return userMapper.activateUser(userid);
    }

}
